<template>
  <div class="container">
    <div class="left">
      <div class="left_top">
        <vue-seamless-scroll :data="notices" :class-option="scrollClassOption">
          <ul class="item">
            <li v-for="item in notices" :key="item.id" style="cursor:pointer">
              <a :href="`/notices/preview/${item.id}`" target="_blank"> {{ item.typeName }}</a>
              <a :href="`/notices/preview/${item.id}`" target="_blank"> {{ item.createTime }}</a>
              <a :href="`/notices/preview/${item.id}`" target="_blank" style="color: #dd6161">{{
                item.title
              }}</a>
              <a :href="`/notices/preview/${item.id}`" target="_blank" style="color: #dd6161">{{
                item.summary
              }}</a>
            </li>
          </ul>
        </vue-seamless-scroll>
      </div>
      <div class="login-bg">
        <img :src="loginLogoBackgroundUrl" alt="注册背景图" />
      </div>
    </div>
    <div class="right">
      <el-card class="login-wrapper">
        <div>
          <img :src="systemLogoUrl" style="width: 272px;height: 92px" alt="系统LOGO" />
        </div>

        <el-form class="login-form" ref="form" :model="formData" label-width="0" :rules="formRules">
          <!-- <div class="login-form"> -->
          <el-form-item prop="username">
            <el-input placeholder="请输入手机号" v-model="formData.username">
              <font-awesome-icon :icon="['fas', 'user']" slot="prepend"> </font-awesome-icon>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input placeholder="请输入密码" type="password" v-model="formData.password">
              <font-awesome-icon :icon="['fas', 'lock']" slot="prepend"> </font-awesome-icon>
            </el-input>
          </el-form-item>
          <el-form-item prop="resPassword">
            <el-input placeholder="请确认密码" type="password" v-model="formData.resPassword">
              <font-awesome-icon :icon="['fas', 'lock']" slot="prepend"> </font-awesome-icon>
            </el-input>
          </el-form-item>

          <div style="margin-top: 12px;">
            <el-button type="primary" @click="submitForm('form')">注 册</el-button>
          </div>
          <div style="margin-top: 12px;">
            <el-button type="text" size="mini" @click="downloadDialog = true">
              推荐浏览器下载
            </el-button>

            <el-dialog
              :close-on-click-modal="false"
              :visible.sync="downloadDialog"
              title="推荐浏览器下载"
            >
              <el-tabs type="border-card" stretch="true" style="width: 100%;" v-model="showSystem">
                <el-tab-pane style="margin-top: 4px;" label="Windows版本" name="Windows">
                  适用于 Windows 10/8.1/8/7 64 位
                  <!--<a :href="`${browserDownloadURL}${chromeForWindows}`">
                                    <span>下载</span></a>-->
                </el-tab-pane>
                <el-tab-pane style="margin-top: 4px;" label="Mac" name="Mac">
                  适用于 Mac OS X 10.8 或更高版本
                  <!--<a :href="`${browserDownloadURL}${chromeForMac}`">
                                    <span>下载</span></a>-->
                </el-tab-pane>
                <el-tab-pane style="margin-top: 4px;" label="Linux" name="Linux">
                  适用于 Linux fedora 和 openSUSE 系统
                  <!--<a :href="`${browserDownloadURL}${chromeForLinux}`">
                                    <span>下载</span></a>-->
                </el-tab-pane>
              </el-tabs>
            </el-dialog>
          </div>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import moment from 'moment/moment'
import VueSeamlessScroll from 'vue-seamless-scroll'

import { $_saveRegistryUser, $_checkUserPhone } from '../network/service'

export default {
  name: 'Login',
  components: {
    VueSeamlessScroll
  },
  data() {
    var checkUserPhone = async (rule, value, callback) => {
      try {
        const res = await $_checkUserPhone(value)
        if (res.code === 200) {
          if (res.data.isExists) {
            this.$message.error('手机号已被注册！')
            callback(new Error('手机号已被注册'))
          } else {
            callback()
          }
        } else {
          callback(new Error('网络错误，请重试！'))
        }
      } catch {
        callback(new Error('网络错误，请重试！'))
      }
    }
    return {
      notices: [],
      scrollClassOption: {
        // 轮播鼠标控制停止
        hoverStop: true,
        // 轮播速度
        step: 0.4,
        // 开始无缝滚动最小数据长度
        limitMoveNum: 1,
        direction: 1, // 0 往下 1 往上 2向左 3向右
        switchDisabledClass: 'NO'
      },
      // 系统logo
      systemLogoUrl: '/images/logo-new.png',
      // 登录背景图
      loginLogoBackgroundUrl: '/images/login-bg.png',

      formData: {
        username: '',
        password: '',
        resPassword: ''
      },
      formRules: {
        username: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          {
            message: '请输入正确的手机号',
            pattern: /^(1)[0-9]{10}$/,
            trigger: 'blur'
          },
          {
            validator: checkUserPhone,
            trigger: 'blur'
          }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        resPassword: [{ required: true, message: '请再次输入密码', trigger: 'blur' }]
      },

      downloadDialog: false
    }
  },

  mounted() {
    this.$store.commit('stateInit')
    this.noticesRequest()
  },

  computed: {
    showSystem() {
      const p = navigator.platform
      if (p.indexOf('Win') === 0) {
        return 'Windows'
      }
      if (p.indexOf('Mac') === 0) {
        return 'Mac'
      }
      if (p === 'X11' || p.indexOf('Linux') === 0) {
        return 'Linux'
      }

      return 'Windows'
    }
  },

  methods: {
    // 识别关键字以 PROXY- 开头
    async noticesRequest() {
      try {
        await this.$axios({
          // 详见 axios 请求配置项
          method: 'GET',
          url: '/notices/bare'
        }).then(res => {
          // 请求失败
          if (res.data.code !== 200) {
            throw new Error(res.data)
          }

          // 请求成功
          const result = res.data
          // 查询结果数据
          this.notices = []
          result.data.forEach(t => {
            const item = {
              id: t.id,
              typeName: t.typeName,
              createTime: moment(t.createTime).format('YYYY-MM-DD'),
              title: t.title,
              summary: t.summary
            }
            this.notices.push(item)
          })
        })
      } catch (e) {
        // 跳出
      }
    },

    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log(this.formRules)
          if (this.formData.password !== this.formData.resPassword) {
            this.$message.error('两次输入密码不一致！')
            return
          }
          this.$_saveRegistryUser()
        } else {
          return false
        }
      })
    },

    async $_saveRegistryUser() {
      const res = await $_saveRegistryUser({
        passWord: this.formData.password,
        phone: this.formData.username
      })
      if (res.code === 200) {
        this.$message.success('注册成功，正在为您跳转！')
        setTimeout(() => {
          this.$router.replace({ path: '/login' })
        }, 500)
      } else {
      }
    },

    async userLogin() {
      return

      // 使用 try catch模式
      try {
        await this.$axios({
          method: 'POST',
          url: '/login',
          params: {
            username: this.username,
            password: this.password
          }
        }).then(res => {
          if (res.data.code === 500) {
            this.$message.warning('用户已被冻结，请联系管理员处理')
            return
          }
          if (res.data.code !== 200) {
            // 请求失败
            throw new Error(res.data)
          }
          // 请求成功
          const result = res.data.data

          const platform = {
            name: '浦东医院病理平台'
          }
          const user = {
            id: result.userInfo.id,
            name: result.userInfo.name,
            headImgUrl: result.userInfo.headUrl
          }
          const permissionList = result['ui-item']
          // 存储缓存数据
          this.$store.commit('setPlatform', platform)
          this.$store.commit('setUser', user)
          this.$store.commit('setPermissionList', permissionList)
          this.$store.commit('loginTimeFlash')
          // 设置登陆后的跳转页
          this.$store.commit('setPropertyGeneral', {
            key: 'nowRoute',
            value: permissionList[0].permissionList[0].route
          })

          this.$router.push({
            path: permissionList[0].permissionList[0].route
          })
          this.$axios({
            method: 'GET',
            url: `/institutions/${result.userInfo.institutionId}`
          }).then(res2 => {
            if (res2 && res2.data.code === 200) {
              const info = res2.data.data
              const institution = {
                id: info.id,
                name: info.name,
                canConsultation: info.canConsultation,
                canFinalVerify: info.canFinalVerify
              }
              this.$store.commit('setInstitution', institution)
            }
          })
        })
      } catch (e) {
        this.$message.info('登录失败，请刷新页面后再次尝试')
      }
    }
  }
}
</script>

<style scoped>
.left {
  float: left;
  width: 50%;
  height: 400px;
}
.right {
  width: 50%;
  margin-left: 50%;
  height: 400px;
}
.left_top {
  width: 100%;
  margin-top: 10px;
  height: 100px;
  overflow: hidden;
  font-size: small;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.left_top a {
  color: #266eff;
  text-decoration: blink;
  background: #ffffff;
}
.container {
  width: 1100px;

  margin: 0 auto;
}
.login-bg {
  margin-left: 35px;
  margin-top: 10px;
  float: left;
}

.login-wrapper {
  width: 420px;

  padding: 16px;

  margin-top: 50px;

  background: #ffffff;

  /*border-radius: 2px;*/
  /*box-shadow: 2px 1px 3px 1px rgba(26, 26, 26, 0.1);*/
  /*box-sizing: border-box;*/

  text-align: center;

  float: right;
}

.login-form {
  margin-top: 32px;
}

.login-form div {
  margin: 10px 20px 8px 6px;
  border-bottom: #f4f4f4 1px;
}

.login-form button {
  width: 100%;
  margin: 10px 20px 8px 6px;
}
</style>
